// src/services/MessageService.ts
import { v4 as uuidv4 } from 'uuid';
import {ContentType} from "../type/Info.ts";
import {EventSourceWrapper} from "./EventSourceWrapper.ts";
import {ChatMessage} from "../type/EventSourceConfig.ts";

type MessageHandler = {
    setHistoryContent: (updater: (prev: ChatMessage[]) => ChatMessage[]) => void;
    setContent: (content: string) => void;
    setStreamId: (id: string | null) => void;
    esInstance: EventSourceWrapper; // SSE连接配置类型需根据实际SDK定义
};

export class MessageService {
    private botMessageId: string | null = null;

    constructor(private handler: MessageHandler) {}
    public send = async (content: string) => {
        if (!this.validateInput(content)) return;
        this.addUserMessage(content);
        this.prepareBotResponse();

        try {
             await this.establishSSEConnection(content);
        } catch (error) {
            this.handleError(error as Error);
        } finally {
            this.cleanup();
        }
    };

    private validateInput = (content: string): boolean => {
        const trimmed = content.trim();
        if (!trimmed) {
            console.warn('空消息被拦截');
            return false;
        }
        return true;
    };

    private addUserMessage = (content: string) => {
        this.handler.setHistoryContent(prev => [
            ...prev,
            { id: uuidv4(), author: 'User', text: content }
        ]);
    };

    private prepareBotResponse = () => {
        this.botMessageId = uuidv4();
        this.handler.setHistoryContent(prev => [
            ...prev,
            {
                id: this.botMessageId,
                author: 'Assistance',
                text: 'AI正在思考中...',
                isStreaming: true
            }
        ]);
        this.handler.setStreamId(this.botMessageId);
    };

    private establishSSEConnection = (content: string) => {
        return new Promise<void>((resolve, reject) => {
            try {
                this.handler.esInstance.setConfig({
                    onMessage: (chunk: string) =>{
                        this.handleChunk(chunk);
                    }
                });
                this.handler.esInstance.setConfig({
                    queryParams:{
                        content,
                        contentType: ContentType.TXT
                    }
                });
                this.handler.esInstance.setConfig({
                    onEnd: (arg) => {
                        console.log(arg)
                        resolve();
                    }
                })
                this.handler.esInstance.connect();
                this.handler.setContent('');
            } catch (error) {
                reject(error);
            }
        });
    };

    private handleChunk = (chunk: string) => {
        if (!this.botMessageId) return;
        this.handler.setHistoryContent(prev =>
            prev.map(msg =>
                msg.id === this.botMessageId
                    ? {
                        ...msg,
                        text: msg.text === 'AI正在思考中...'
                            ? chunk
                            : msg.text + chunk.replace(/\\n/g, '\n')
                    }
                    : msg
            )
        );
    };

    private handleError = (error: Error) => {
        console.error('消息服务错误:', error);
        if (!this.botMessageId) return;
        this.handler.setHistoryContent(prev =>
            prev.map(msg =>
                msg.id === this.botMessageId
                    ? { ...msg, text: '请求失败，请重试', isStreaming: false }
                    : msg
            )
        );
    };

    private cleanup = () => {
        this.handler.setStreamId(null);
        this.handler.setHistoryContent(prev =>
            prev.map(msg =>
                msg.id === this.botMessageId
                    ? { ...msg, isStreaming: false }
                    : msg
            )
        );
        this.botMessageId = null;
    };
}